package com.atguiju.connection;

import org.junit.Test;

import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionTest {

    //方式1
    @Test
    public void testConnection1() throws SQLException {
        Driver driver = new com.mysql.jdbc.Driver();
        String url = "jdbc:mysql://localhost:3306/test";
        //用户名和密码封装在这里
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");
        Connection conn = driver.connect(url, info);
        System.out.println(conn);
    }

    //方式2，对方式1的迭代
    @Test
    public void testConnection2() throws Exception {
        //1.获取Driver对象，通过反射获取
        Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();
        String url = "jdbc:mysql://localhost:3306/test";
        //用户名和密码封装在这里
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "root");
        Connection conn = driver.connect(url, info);
        System.out.println(conn);

    }
    //方式3，对方式2的迭代
    @Test
    public void testConnection3() throws Exception {
        Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
        DriverManager.registerDriver((Driver) clazz.newInstance());
        String url = "jdbc:mysql://localhost:3306/test";
        Connection conn = DriverManager.getConnection(url, "root", "root");
        System.out.println(conn);
    }
    //方式5，将数据库链接的基本信息声明在配置文件中，通过读取配置文件的方式，获取连接
    @Test
    public void testConnection5() throws Exception {
        //1.读取配置文件的基本信息
        InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        Class<?> clazz = Class.forName(pros.getProperty("driverClass"));


        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

}
